package com.ytjj.qmyx.mall.controller;

import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.model.GroupBuyInfo;
import com.ytjj.qmyx.mall.model.GroupBuyUserRel;
import com.ytjj.qmyx.mall.model.response.groupbuy.GroupBuyOrderDetailResponse;
import com.ytjj.qmyx.mall.model.response.groupbuy.ProcessGroupBuyListResponse;
import com.ytjj.qmyx.mall.service.GroupActivityService;
import com.ytjj.qmyx.mall.service.YxGroupBuyInfoService;
import com.ytjj.qmyx.mall.service.YxGroupBuyUserRelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拼团
 */
@RestController
@RequestMapping("/group")
@Slf4j
public class GroupController extends BaseController {
    @Autowired
    private GroupActivityService groupActivityService;
    @Autowired
    private YxGroupBuyInfoService yxGroupBuyInfoService;
    @Autowired
    private YxGroupBuyUserRelService yxGroupBuyUserRelService;

    /**
     * 判断新老拼团用户  规则 参与过3次或以上次数的为老用户
     * @return 1-老用户 0-新用户
     */
    @GetMapping("/newAndOldUser")
    public CommonResult checkNewAndOldUser() {
        log.info("===checkNewAndOldUser===");
        try {
            String token = TokenUtil.getToken();
            if (!StringUtils.isEmpty(token)) {
                UsersResponse usersResponse = getCurrentUser();
                Integer num = groupActivityService.getMyGroupNum(usersResponse.getId());
                if (null == num || num < 3) {
                    return CommonResult.success(0);
                }
                return CommonResult.success(1);
            }
        } catch (Exception e) {
            log.info("==={}===", e);
        }

        return CommonResult.success(0);
    }

    /**
     * 精选拼团商品列表
     * @param pageSize
     * @param pageNum
     * @param activityType
     * @return
     */
    @GetMapping("/list")
    public CommonResult queryProductList(@RequestParam("pageSize") Integer pageSize,
                                         @RequestParam("pageNum") Integer pageNum,
                                         @RequestParam("activityType") String activityType) {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("===未登录用户===");
        }
        if (null != usersResponse) {
            return groupActivityService.getGroupWorkAll(pageSize, pageNum, activityType, usersResponse.getId());
        }else {
            return groupActivityService.getGroupWorkAll(pageSize, pageNum, activityType, null);
        }
    }

    /**
     * 快速参与拼团列表
     * @param pageSize
     * @param pageNum
     * @param activityType
     * @return
     */
    @GetMapping("/quick_list")
    public CommonResult queryQuickList(@RequestParam("pageSize") Integer pageSize,
                                       @RequestParam("pageNum") Integer pageNum,
                                       @RequestParam("activityType") String activityType) {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("===未登录用户===");
        }
        if (null != usersResponse) {
            return groupActivityService.getQuickGroupWorkAll(pageSize, pageNum, activityType, usersResponse.getId());
        } else {
            return groupActivityService.getQuickGroupWorkAll(pageSize, pageNum, activityType, null);
        }
    }

    /**
     * 我的拼团列表
     * @param pageSize
     * @param pageNum
     * @param activityType
     * @param status
     * @return
     */
    @GetMapping("/my_group_list")
    public CommonResult queryMyGroupList(@RequestParam("pageSize") Integer pageSize,
                                         @RequestParam("pageNum") Integer pageNum,
                                         @RequestParam("activityType") String activityType,
                                         @RequestParam(value = "status" ,required = false) Integer status) {
        UsersResponse usersResponse = getCurrentUser();
        return groupActivityService.getMyGroupList(pageSize, pageNum, activityType, status, usersResponse.getId());
    }

    @GetMapping("/banners")
    public CommonResult queryBannersByActivity(@RequestParam("activityType") String activityType) {
        return groupActivityService.queryBannersByActivity(activityType);
    }

    /**
     * 拼团商品详情中的团信息
     * @return
     */
    @GetMapping("/detail/{id}")
    public CommonResult queryDetail(@PathVariable("id") Integer id) {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("===未登录用户===");
        }
        if (null != usersResponse) {
            return CommonResult.success(groupActivityService.queryDetail(id, usersResponse.getId()));
        }else {
            return CommonResult.success(groupActivityService.queryDetail(id, null));
        }
    }

    /**
     * (开团/参团成功)后的订单详情中拼团一些属性
     * @return
     */
    @GetMapping("/group_order_detail")
    public CommonResult queryGroupOrderDetail(@RequestParam(required = false) Integer groupId, @RequestParam(required = false) Integer productId, @RequestParam(required = false) Integer orderId) {
        UsersResponse usersResponse = getCurrentUser();
        GroupBuyOrderDetailResponse groupBuyOrderDetailResponse =
                groupActivityService.queryOrderDetailGroupPropertiesByOrderNo(groupId, productId, usersResponse.getId(), orderId);
        return CommonResult.success(groupBuyOrderDetailResponse);
    }

    /**
     * 精选拼团推荐
     * @return
     */
    @GetMapping("/fine_group_list")
    public CommonResult queryFineGroupList() {
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("===未登录用户===");
        }
        return groupActivityService.queryFineGroupList(usersResponse.getId());
    }

    /**
     * 团成功未中奖，领取红包
     * @param orderNo
     * @return
     */
    @GetMapping("/receive_red_pack")
    public CommonResult receiveRedPack(@RequestParam String orderNo) {
        UsersResponse usersResponse = getCurrentUser();
        return groupActivityService.receiveRedPack(orderNo, usersResponse.getId());
    }

    /**
     * 拼团失败时的团推荐
     * @param productId 商品id
     * @param groupId   团id    两项不能同时为空
     */
    @GetMapping("/process_group_list")
    public CommonResult queryProcessGroupList(@RequestParam(required = false) Integer productId, @RequestParam(required = false) Integer groupId) {
        if (null == productId) {
            GroupBuyInfo groupBuyInfo = yxGroupBuyInfoService.selectById(groupId);//开团信息
            if (null == groupBuyInfo) {
                throw new ApiException("找不到团信息");
            }
            productId = groupBuyInfo.getProductId();
        }
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            log.info("===未登录用户===");
        }
        List<ProcessGroupBuyListResponse> result = yxGroupBuyInfoService.queryProcessGroupBuyList(productId);
        List<ProcessGroupBuyListResponse> myDonotGroups = new ArrayList<>();
        //查询当前用户参与的团
        if (null != usersResponse && null != usersResponse.getId()) {
            List<GroupBuyUserRel> rels = yxGroupBuyUserRelService.queryCurUserJoinGroupId(usersResponse.getId());
            List<Integer> myGroupIds = rels.stream().map(GroupBuyUserRel::getGroupId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(rels)) {
                result.stream().forEach(group -> {
                    if (!myGroupIds.contains(group.getGroupId())) {
                        myDonotGroups.add(group);
                    }
                });
            }else {
                myDonotGroups.addAll(result);
            }
        }else {
            myDonotGroups.addAll(result);
        }
        return CommonResult.success(myDonotGroups);
    }
}
